package cz.spock.core.entity.security;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Id;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.annotation.Unindexed;

/**
 * Implementation of UserDetails interface for spring security
 * 
 * check grantedAuthorities
 * 
 * @author miso
 *
 */
@Entity
@SuppressWarnings("serial")
public class AccountSecurity implements UserDetails {
    
    @Id //login
    private String login;
    
    @Unindexed
    private String password;
    
    @Unindexed
    private List<Key<SpockGrantedAuthority>> grantedAuthorities;
    
    private boolean valid;
    
    // TODO check typing in this method
    public List<GrantedAuthority> getAuthorities() {
        Objectify ofy = ObjectifyService.factory().begin();
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(ofy.get(this.grantedAuthorities).values());
        return authorities;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return login;
    }

    public boolean isAccountNonExpired() {
        return valid;
    }

    public boolean isAccountNonLocked() {
        return valid;
    }

    public boolean isCredentialsNonExpired() {
        return valid;
    }

    public boolean isEnabled() {
        return valid;
    }
    
    
    
    //Getters and setters
    
    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public List<Key<SpockGrantedAuthority>> getGrantedAuthorities() {
        return grantedAuthorities;
    }

    public void setGrantedAuthorities(List<Key<SpockGrantedAuthority>> roles) {
        this.grantedAuthorities = roles;
    }

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}




